package com.ztorn.fiscale.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztorn.common.core.utils.StringUtils;
import com.ztorn.common.core.utils.DateUtils;
import com.ztorn.common.security.utils.SecurityUtils;
import com.ztorn.fiscale.domain.FiscaleProduct;
import com.ztorn.fiscale.mapper.FiscaleProductMapper;
import com.ztorn.fiscale.service.IFiscaleProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Arrays;

/**
 * 智能商品库服务实现
 *
 * @author ztorn
 */
@Service
public class FiscaleProductServiceImpl extends ServiceImpl<FiscaleProductMapper, FiscaleProduct> implements IFiscaleProductService {

    @Autowired
    private FiscaleProductMapper fiscaleProductMapper;

    /**
     * 查询智能商品库列表
     *
     * @param product 智能商品库信息
     * @return 智能商品库集合
     */
    @Override
    public List<FiscaleProduct> selectProductList(FiscaleProduct product) {
        return fiscaleProductMapper.selectFiscaleProductList(product);
    }

    /**
     * 查询智能商品库详细
     *
     * @param productId 商品ID
     * @return 智能商品库信息
     */
    @Override
    public FiscaleProduct selectProductById(Long productId) {
        return fiscaleProductMapper.selectById(productId);
    }

    /**
     * 新增智能商品库
     *
     * @param product 智能商品库信息
     * @return 结果
     */
    @Override
    public int insertProduct(FiscaleProduct product) {
        product.setCreateTime(DateUtils.getNowDate());
        product.setCreateBy(SecurityUtils.getUsername());
        boolean result = this.save(product);
        return result ? 1 : 0;
    }

    /**
     * 修改智能商品库
     *
     * @param product 智能商品库信息
     * @return 结果
     */
    @Override
    public int updateProduct(FiscaleProduct product) {
        product.setUpdateTime(DateUtils.getNowDate());
        product.setUpdateBy(SecurityUtils.getUsername());
        boolean result = this.updateById(product);
        return result ? 1 : 0;
    }

    /**
     * 批量删除智能商品库
     *
     * @param productIds 需要删除的商品ID
     * @return 结果
     */
    @Override
    public int deleteProductByIds(Long[] productIds) {
        boolean result = this.removeByIds(Arrays.asList(productIds));
        return result ? 1 : 0;
    }

    /**
     * 删除智能商品库信息
     *
     * @param productId 商品ID
     * @return 结果
     */
    @Override
    public int deleteProductById(Long productId) {
        boolean result = this.removeById(productId);
        return result ? 1 : 0;
    }

    /**
     * 导入智能商品库数据
     *
     * @param productList 智能商品库数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importProduct(List<FiscaleProduct> productList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(productList) || productList.isEmpty()) {
            throw new RuntimeException("导入商品数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (FiscaleProduct product : productList) {
            try {
                // 验证是否存在这个商品
                LambdaQueryWrapper<FiscaleProduct> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(FiscaleProduct::getProductCode, product.getProductCode());
                FiscaleProduct existProduct = this.getOne(queryWrapper);

                if (StringUtils.isNull(existProduct)) {
                    product.setCreateBy(operName);
                    product.setCreateTime(DateUtils.getNowDate());
                    this.save(product);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、商品 ").append(product.getProductNameCn()).append(" 导入成功");
                } else if (isUpdateSupport) {
                    product.setProductId(existProduct.getProductId());
                    product.setUpdateBy(operName);
                    product.setUpdateTime(DateUtils.getNowDate());
                    this.updateById(product);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、商品 ").append(product.getProductNameCn()).append(" 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、商品 ").append(product.getProductNameCn()).append(" 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、商品 " + product.getProductNameCn() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new RuntimeException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
